<template>
  <div class="container">
    <Header :getGoods="getGoods" />
    <main class="main" @scroll="onScroll">
    <div class="help"></div>
      <div class="main-bottom">
        <GoodsList :goods="visibleGoods" />
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import Header from './Header.vue';
import GoodsList from './GoodsList.vue';
import { getGoodsFromAPI } from '../utils';
import '../css/index.css';
import '../css/goods.css';

interface Goods {
  id: number;
  name: string;
  imgPath: string;
  price: number;
  blurb: string;
  intro: string;
  categoriesId: number;
  createTime: string;
  createUser: string;
}
const goods = ref<Goods[]>([]);
const visibleGoods = ref<Goods[]>([]);
let page = ref<number>(1);
const perPage = 10;
const getGoodsLink = 'http://localhost:8080/goods/allGoods';
const route = useRoute();

const loadMoreGoods = () => {
  const start = (page.value - 1) * perPage;
  const end = page.value * perPage;
  visibleGoods.value.push(...goods.value.slice(start, end));
  page.value++;
};

const onScroll = (event: Event) => {
  const target = event.target as HTMLElement;
  if (target.scrollTop + target.clientHeight >= target.scrollHeight) {
    loadMoreGoods();
  }
};



import CryptoJS from 'crypto-js';

const decryptParameters = (ciphertext: string) => {
  const bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key');
  const originalText = bytes.toString(CryptoJS.enc.Utf8);
  return JSON.parse(originalText);
};

const getGoods = async (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => {
  try {
    page.value = 1;
    goods.value = [];
    visibleGoods.value = [];
    await getGoodsFromAPI(filterObject, getGoodsLink, goods, loadMoreGoods);
  } catch (error: any) {
    console.error('Error fetching goods:', error);
    if (error.response && error.response.status === 404) {
      // 处理 404 错误
    } else if (error instanceof Error) {
      console.error('Error message:', error.message);
      if (error.message === '找不到该商品') {
        visibleGoods.value = [];
      }
    } else {
      console.error('Unknown error:', error);
    }
  }
};
;

const updateGoodsList = () => {
  const encryptedParams = route.query.params as string;  // 获取加密的参数

  if (encryptedParams) {
    // 解密参数
    const decryptedParams = decryptParameters(encryptedParams);

    const filterObject = {
      name: decryptedParams.name,
      platform: decryptedParams.platform,
      sortType: decryptedParams.sortType,
      categoriesId: decryptedParams.categoriesId
    };

    getGoods(filterObject);
  }
};


onMounted(() => {
  updateGoodsList();
});

watch(
  () => route.query,
  () => {
    updateGoodsList();
  }
);
</script>
<style>
.help{
  height: 50px;
}
</style>

